//添加sql
import dict from "@src/models/dict";
import {getID} from "@src/util/util";
import moment from "moment";
import fieldCategory from "@src/models/fieldCategory";
import {Op} from "sequelize";
import Constant from "@src/util/constant";
import region from "@src/models/region";


// 查询字典数据
const findNameCount = async (name: string) => {
  return await dict.count({
    where: {
      name,
    },
  });
};

// 验证分类是否存在
const isCategoryId = async (id: string) => {
  return await dict.findOne({
    where: {
      id,
    },
  });
};

// 验证传入的字典id是否正确
const isTypeId = async (typeId: string) => {
  const count = await fieldCategory.count({
    where: {
      id: typeId,
    },
  });
  // 不存在该分类,反之存在
  return count === 0;
};

// 通过id 查字典类型name
const getName = async (id: string) => {
  return fieldCategory.findOne({
      where: {id},
      attributes: ["name"],
    },
  );
};

// 插入区域数据
const insertRegion = async (name: string, category_id: string) => {
  await region.create({
    id: getID(),
    name,
    category_id,
    images: [],
    videos: [],
    created_at: moment().format("X"),
    visit_num: 0,
  });
};

// 创建字典
const add = async (typeId: string, name: string) => {
  // 字典名字不能重复
  const count = await findNameCount(name);
  if (count === 1) {
    return false;
  }
  // 类型是否存在
  const isCategory = await isTypeId(typeId);
  if (isCategory) {
    return 0;
  }

  const categoryData: any = await getName(typeId);

  const id = getID();
  // 字典创建
  await dict.create({
    id,
    name,
    type_id: typeId,
    created_at: moment().format("X"),
    updated_at: moment().format("X"),
  });
  // 如果创建了区域管理，就需要插入一条区域数据
  if (categoryData.name === "区域管理") {
    await insertRegion(name, id);
  }
  return true;
};

// 更新字典
const update = async (id: string, typeId: string, name: string) => {
  // 类型是否存在
  const isCategory = await isTypeId(typeId);
  if (isCategory) {
    return 0;
  }
  await dict.update({
    type_id: typeId,
    name,
  }, {
    where: {
      id,
    },
  });
  return true;
};

// 删除字典
const _delete = async (id: string) => {
  await dict.destroy({
    where: {id},
  });
};

// 查询数据字典
const list = async (offset: number, limit: number, filters: { name?: string, type_id?: string }) => {
  const whereObj: any = {};
  for (const v in filters) {
    if (v === "name" && filters[v]) {
      whereObj[v] = {
        [Op.substring]: filters[v],
      };
    }
    if (v === "type_id" && filters[v]) {
      whereObj[v] = filters[v];

    }
  }
  const {count, rows} = await dict.findAndCountAll(
    {
      attributes: ["id", "type_id", "created_at", "name"],
      where: whereObj,
      // 从第几条开始
      offset,
      // 查询多少条
      limit,
      //关联查询
      include: [
        {
          attributes: ["name", "id"],
          model: fieldCategory,
        },
      ],
    },
  );
  return {
    count,
    rows,
  };
};

// 查询分类下的字典
const category = async (type_id: string) => {
  const isCategory = await isTypeId(type_id);
  if (isCategory) {
    return isCategory;
  }
  return await dict.findAll({
    where: {
      type_id,
    },
  });
};


// 通过id查字典id
const getTypeId = async (id: string) => {
  return await dict.findOne({
    attributes: ["type_id"],
    where: {
      id,
    },
  });
};


export default {
  add,
  update,
  _delete,
  list,
  category,
  isTypeId,
  isCategoryId,
  getTypeId
};